package com.bj58.mis.apm.server.core.service.impl;

import com.bj58.mis.apm.server.core.mapper.CurdMapper;
import com.bj58.mis.apm.server.core.service.CurdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

public abstract class MybatisCurdService<Model, ID, Mapper extends CurdMapper<Model, ID>> implements CurdService<Model, ID> {
	/**
	 * 日志，子类可以使用。
	 */
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected Mapper mapper;


	/**
	 * 事务回滚
	 */
	protected void rollback() {
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	}

	/**
	 * 保存前校验
	 *
	 * @param model
	 * @throws Exception
	 */
	protected void validateInsert(Model model) {

	}

	/**
	 * 保存前校验
	 *
	 * @param model
	 * @throws Exception
	 */
	protected void validateUpdate(Model model) {

	}

	/**
	 * 新增
	 *
	 * @param model
	 */
	@Override
	public void insert(Model model) {
		validateInsert(model);
		mapper.insert(model);
	}

	/**
	 * 修改
	 *
	 * @param model
	 */
	@Override
	public void update(Model model) {
		validateUpdate(model);
		mapper.update(model);
	}

	/**
	 * 删除model
	 *
	 * @param id
	 */
	@Override
	public void delete(ID id) {
		validateDelete(id);
		mapper.delete(id);
	}

	/**
	 * 删除前校验
	 *
	 * @param id
	 */
	protected void validateDelete(ID id) {

	}

	/**
	 * 删除多个model
	 *
	 * @param ids
	 */
	@Override
	public void delete(List<ID> ids) {
		for (ID id : ids) {
			validateDelete(id);
		}
		for (ID id : ids) {
			mapper.delete(id);
		}
	}

	/**
	 * 获取model
	 *
	 * @param id
	 * @return
	 */
	@Override
	public Model get(ID id) {
		return mapper.get(id);
	}

	/**
	 * 查询model数据
	 *
	 * @param parameter
	 * @return
	 */
	@Override
	public List<Model> query(Object parameter) {
		return mapper.query(parameter);
	}
}